import 'package:flutter/material.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:get/get.dart';
import 'package:jxchmz/%E4%BB%93%E7%AE%A1/%E7%89%A9%E8%B5%84%E5%85%A5%E5%BA%93/GoodsEntry.dart';
import 'package:jxchmz/%E4%BB%93%E7%AE%A1/%E7%89%A9%E8%B5%84%E5%85%A5%E5%BA%93/Notes.dart';
import 'package:jxchmz/API/%E5%BA%93%E5%AD%98%E7%AE%A1%E7%90%86/KuCunManager.dart';
import 'package:jxchmz/Getx%E5%B7%A5%E5%85%B7/GetxTools.dart';

class PrfOrderList extends StatefulWidget {
  @override
  _PrfOrderListState createState() => new _PrfOrderListState();
}

class _PrfOrderListState extends State<PrfOrderList> {
  //选择入库类型
  TextEditingController SelectEntryController = new TextEditingController();

  //订单列表
  List OrderList = [];

  // 当前页数
  int _page = 1;

  // 是否还有
  bool _hasMore = true;

  // 滚动控制器
  ScrollController _scrollController = new ScrollController();
  var SelectEntry = [{"name": "Purchaseinbound".tr, "id": 0}, {"name": "Returntothewarehouse".tr, "id": 1}];
  var SelectEntryData = ["Purchaseinbound".tr, "Returntothewarehouse".tr];
  var SelectEntryName;
  var SelectEntryId;


//页面加载完成时
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // 监听滚动事件
    _scrollController.addListener(() {
      var maxScroll = _scrollController.position.maxScrollExtent;
      var pixel = _scrollController.position.pixels;
      if (maxScroll == pixel) {
        if (_hasMore) {
          _page++;
          if (SelectEntryId == 0) {
            //获取采购订单
            GetlistPrfOrder();
          }
          if (SelectEntryId == 1) {
            //获取销售订单
            GetlistSaleOrder();
          }
        }
      }
    });
    // Future.delayed(Duration.zero,(){
    //   //获取采购订单
    //   GetlistPrfOrder();
    // });
  }

  ///页面卸载
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  ///当 State 被暂时从视图树中移除时，会调用这个方法，同时页面切换时，也会调用。
  @override
  void deactivate() {
    // TODO: implement dispose
    super.deactivate();
  }

  ///在 initState() 之后调用，当 State 对象的依赖关系发生变化时，该方法被调用，初始化时也会调用。
  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
  }

  // TODO: add state variables and methods
  @override
  Widget build(BuildContext context) {
    // TODO: add widget build method
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          backgroundColor: Colors.white,
          title: Text("Listofinboundorders".tr, style: TextStyle(fontSize: 15, color: Colors.black),),
          centerTitle: true,
          elevation: 0,
          iconTheme: IconThemeData(
              color: Colors.black
          ),
          actions: [
            TextButton(onPressed: (){
            //进入入库记录
            Get.to(Notes());
            }, child: Row(
              children: [
                Text("记录",style: TextStyle(fontSize: 14,color: Colors.black),),
                Container(
                  width: 3,
                ),
                Icon(Icons.article_outlined,color: Colors.black,size: 16,),

              ],
            ))
          ],
        ),
        body: Container(
            padding: EdgeInsets.all(15),
            child: Column(
              children: [
                //选择入库类型
                GestureDetector(
                  child: TextField(
                    controller: SelectEntryController,
                    enabled: false,
                    decoration: InputDecoration(
                        hintText: "Pleaseselectashippingtype".tr,
                        suffixIcon: Icon(Icons.keyboard_arrow_down),
                        icon: Container(
                          width: 70,
                          child: Text("Inboundtype".tr),
                        )
                    ),

                  ),
                  onTap: () {
                    //打开选择入库类型
                    ShowPickSelectEntry();
                  },
                ),
                Container(
                  height: 15,
                ),
                //入库列表
                Container(
                  alignment: Alignment.centerLeft,
                  child: SelectEntryId==0?Text(
                    "listofpurchaseorders".tr+"(${OrderList.length})",
                    style: TextStyle(fontWeight: FontWeight.w600, fontSize: 20),
                  ):Text("listofsalesorders".tr+"(${OrderList.length})",
                    style: TextStyle(fontWeight: FontWeight.w600, fontSize: 20),),
                ),
                Expanded(
                  child: ListView.separated(
                    controller: _scrollController,
                    itemBuilder: (context, index) {
                      return GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        child: Container(
                          margin: EdgeInsets.only(top: 15),
                          child: Column(
                            children: [
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Container(
                                    child: Text("Ordernumber".tr+":${OrderList[index]['billNo']}"),
                                    alignment: Alignment.centerLeft,
                                  ),
                                  SelectEntryId==0?Container(
                                    child: Text("${OrderList[index]['settleQty'].toInt() < OrderList[index]['qty'].toInt() ? "Warehousing".tr : "Completed".tr}",
                                      style: TextStyle(
                                          color: OrderList[index]['settleQty'].toInt() < OrderList[index]['qty'].toInt() ? Colors.orange:Colors.green),),
                                    alignment: Alignment.centerLeft,
                                  ):Container(),
                                ],

                              ),
                              Container(
                                height: 5,
                              ),
                              SelectEntryId==0?Container(
                                child: Row(
                                  children: [
                                    Text("Thenumberofplannedputaways".tr+"：${OrderList[index]['qty'].toInt().toString()}"),
                                    Text("Theactualnumberofincominggoods".tr+"：${OrderList[index]['settleQty'].toInt().toString()}"),
                                  ],
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                ),
                              ):Container(
                                child: Row(
                                  children: [
                                    Text("Numbersold".tr+"：${OrderList[index]['qty'].toInt().toString()}"),
                                    Text("Thenumberofreturns".tr+"：${OrderList[index]['settleQty'].toInt().toString()}"),
                                  ],
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                ),
                              )
                            ],
                          ),
                        ),
                        onTap: () {
                          //前往物资入库
                          Get.to(GoodsEntry(), arguments: {"Order": OrderList[index], "goodsType": SelectEntryId})!.then((value) {
                            print("返回订单列表，刷新订单");
                            _page = 1;
                            _hasMore = true;
                            OrderList = [];
                            if (SelectEntryId == 0) {
                              //获取采购订单
                              GetlistPrfOrder();
                            }
                            if (SelectEntryId == 1) {
                              //获取销售订单
                              GetlistSaleOrder();
                            }
                          });
                        },

                      );
                    },
                    itemCount: OrderList.length,
                    separatorBuilder: (BuildContext context, int index) {
                      return Divider();
                    },),
                )
              ],
            )
        )
    );
  }

  //弹窗入库类型
  ShowPickSelectEntry() {
    Pickers.showSinglePicker(
      context,
      // 使用只有Name的数组
      data: SelectEntryData,
      selectData: SelectEntryName,
      onConfirm: (p, position) {
        // 提取所选的数据id
        SelectEntryId = SelectEntry[position]['id'];
        //所选的名称
        SelectEntryName = p;
        //给输入框赋值
        SelectEntryController = new TextEditingController(text: p);
        setState(() {});
        //获取相对应的订单
        _page = 1;
        _hasMore = true;
        OrderList = [];
        if (SelectEntryId == 0) {
          //获取采购订单
          GetlistPrfOrder();
        }
        if (SelectEntryId == 1) {
          //获取销售订单
          GetlistSaleOrder();
        }
      },
    );
  }

  //获取采购订单
  GetlistPrfOrder() async {
    //搜索参数
    var data = {
      "pageNum": _page,
      "pageSize": 10,
      "reasonable": false,
      "isApproverStatus":1
    };
    var ResponseData = await KuCunManager().GetPrfOrder(data);
    if (ResponseData['code'] == 200) {
      var List = [];
      List = ResponseData['rows'];
      if (List.length <= 0) {
        // 关闭加载
        this._hasMore = false;
      } else {
        List.forEach((element) {
          OrderList.add(element);
        });
      }
    } else {
      new GetxTools().ErrorToast("Purchaseorderinformationacquisitionfailed".tr);
    }
    setState(() {});
  }

  //获取销售订单
  GetlistSaleOrder() async {
    //搜索参数
    var data = {
      "pageNum": _page,
      "pageSize": 10,
      "reasonable": false,
      "approvalResultType":1
    };
    var ResponseData = await KuCunManager().GetSaleOrder(data);
    if (ResponseData['code'] == 200) {
      var List = ResponseData['rows'];
      if (List.length <= 0) {
        // 关闭加载
        this._hasMore = false;
      } else {
        List.forEach((element) {
          OrderList.add(element);
        });
      }
    } else {
      new GetxTools().ErrorToast("Failedtogetsalesorderinformation".tr);
    }
    setState(() {});
  }
}
